<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="border-left: 6px solid #409eff; padding-left: 8px">航班管理</span>
      </div>
      <div class="text item">
        <!-- 搜索框 -->
        <el-input v-model="inputNo" placeholder="请输入航班号" style="width: 180px;"></el-input>
        <el-button
          type="primary"
          @click="showAddDialog"
          style="float: right;margin-bottom: 5px;"
        >添加航班</el-button>
        <el-table :data="filteredFli" stripe>
          <el-table-column label="航班信息" align="center">
            <template slot-scope="{ row }">
              <div>
                <img src="../assets/noImg.png" class="airline-icon" />
                <div style="color: #0086f6">
                  {{ row.airline }}
                  -
                  {{ row.flightNumber }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="cityFrom" label="始发城市" align="center"></el-table-column>
          <el-table-column prop="cityTo" label="到达城市" align="center"></el-table-column>
          <el-table-column prop="departureAirport" label="始发机场" align="center"></el-table-column>
          <el-table-column prop="arrivalAirport" label="到达机场" align="center"></el-table-column>
          <el-table-column prop="departureTime" label="起飞时间" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.departureTime) }}</template>
          </el-table-column>
          <el-table-column prop="arrivalTime" label="到达时间" align="center">
            <template slot-scope="scope">{{ formatDate(scope.row.arrivalTime) }}</template>
          </el-table-column>
          <el-table-column prop="salesStatus" label="售卖状态" align="center">
            <template
              slot-scope="scope"
            >{{ scope.row.salesStatus === 1 ? "售卖中" : (scope.row.salesStatus === 0 ? "停售" : "")}}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="{row}">
              <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteRow(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page.sync="pageNo"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            :total="counts"
            v-if="tableData.length > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </div>
    </el-card>

    <el-dialog :visible.sync="dialogVisible" title="添加航班">
      <el-form :model="flightForm" label-width="100px" ref="flightForm" :rules="rules">
        <el-form-item label="航空公司" prop="airline">
          <el-input v-model="flightForm.airline"></el-input>
        </el-form-item>
        <el-form-item label="航班号" prop="flightNumber">
          <el-input v-model="flightForm.flightNumber"></el-input>
        </el-form-item>
        <el-form-item label="始发城市" prop="cityFrom">
          <el-select v-model="flightForm.cityFrom" placeholder="请选择始发城市" name="cityFrom">
            <el-option
              v-for="city in cityList"
              :key="city.value"
              :label="city.label"
              :value="city.value"
              :disabled="city.value === flightForm.cityTo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="到达城市" prop="cityTo">
          <el-select v-model="flightForm.cityTo" placeholder="请选择到达城市" name="cityTo">
            <el-option
              v-for="city in cityList"
              :key="city.value"
              :label="city.label"
              :value="city.value"
              :disabled="city.value === flightForm.cityFrom"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="始发机场" prop="departureAirport">
          <el-input v-model="flightForm.departureAirport"></el-input>
        </el-form-item>

        <el-form-item label="到达机场" prop="arrivalAirport">
          <el-input v-model="flightForm.arrivalAirport"></el-input>
        </el-form-item>

        <el-form-item label="起飞时间" prop="departureTime">
          <el-date-picker
            v-model="flightForm.departureTime"
            type="datetime"
            :picker-options="pickerOptions"
            placeholder="请选择起飞时间"
          />
        </el-form-item>

        <el-form-item label="到达时间" prop="arrivalTime">
          <el-date-picker
            v-model="flightForm.arrivalTime"
            type="datetime"
            :picker-options="pickerOptions"
            placeholder="请选择到达时间"
          />
        </el-form-item>

        <el-form-item label="售卖状态">
          <el-radio-group v-model="flightForm.salesStatus">
            <el-radio :label="0">停售</el-radio>
            <el-radio :label="1">售卖中</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="舱位" prop="cabins">
          <div style="border: 1px solid #DCDFE6; ">
            <div
              v-for="(cabin, index) in flightForm.cabins"
              :key="index"
              style="margin: 15px 0 0 15px;"
            >
              <el-row :key="'row' + index">
                <el-col :span="6">
                  <el-form-item :prop="'cabins.' + index + '.cabin'">
                    <el-input v-model="cabin.cabin" placeholder="请输入舱位名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5" :offset="1">
                  <el-form-item :prop="'cabins.' + index + '.price'">
                    <el-input v-model="cabin.price" placeholder="请输入价格"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="3" :offset="9">
                  <el-button
                    icon="el-icon-circle-close"
                    @click="removePassenger(index)"
                    style="color: red;"
                  />
                </el-col>
              </el-row>
            </div>
            <div style="padding-left: 15px;">
              <el-button
                type="text"
                icon="el-icon-plus"
                @click="addPassenger"
                :disabled="flightForm.cabins.length >= 4"
              >添加舱位</el-button>
              <span
                v-show="flightForm.cabins.length >= 4"
                style="margin-left: 10px; color: red;"
              >*最多4个</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitFlightForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
export default {
  data() {
    return {
      dialogVisible: false,
      inputNo: "",
      pageNo: 1,
      pageSize: 5,
      counts: 0, // 总条数，用于分页
      tableData: [],

      flightForm: {
        id: "",
        airline: "",
        flightNumber: "",
        cityFrom: "",
        cityTo: "",
        departureAirport: "",
        arrivalAirport: "",
        departureTime: "",
        arrivalTime: "",
        salesStatus: "",
        cabins: [{ cabin: "", price: "", flightId: "" }],
      },
      cityList: [
        { label: "北京", value: "北京" },
        { label: "上海", value: "上海" },
        { label: "广州", value: "广州" },
        { label: "深圳", value: "深圳" },
      ],
      pickerOptions: {
        disabledDate(time) {
          const today = new Date();
          return time.getTime() < today.setHours(0, 0, 0, 0); //禁用今天以前的日期
        },
      },
      rules: {
        airline: [{ required: true, message: "不能为空", trigger: "blur" }],
        flightNumber: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        cityFrom: [{ required: true, message: "不能为空", trigger: "change" }],
        cityTo: [{ required: true, message: "不能为空", trigger: "change" }],
        departureAirport: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        arrivalAirport: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        departureTime: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        arrivalTime: [{ required: true, message: "不能为空", trigger: "blur" }],
        cabins: [
          {
            validator: this.validateCabins,
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getFlightList();
  },
  computed: {
    filteredFli() {
      return this.tableData.filter((t) => {
        return (
          t.flightNumber.indexOf(this.inputNo) !== -1 ||
          t.cityFrom.indexOf(this.inputNo) !== -1 ||
          t.cityTo.indexOf(this.inputNo) !== -1
        );
      });
    },
  },
  methods: {
    //单页条数改变时
    async handleSizeChange(val) {
      this.pageSize = val;
      this.getFlightList();
    },
    // 当前页码改变时
    async handleCurrentChange(val) {
      this.pageNo = val;
      this.getFlightList();
    },
    //查询航班列表
    async getFlightList() {
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
      };
      await this.$axios
        .post("/api/flight/selPage", params, {
          headers: { Authorization: "emp" },
        })
        .then((res) => {
          if (res.data.code === 1) {
            this.counts = res.data.data.counts;
            this.tableData = [...res.data.data.items];
          } else if (res.data.code === 0) {
            this.$message.error(res.data.msg);
          }
        })
        .catch((error) => {
          // 处理请求失败的错误
          this.$message.error("net ero");
        });
    },
    //提交编辑或添加内容
    async submitFlightForm() {
      // 处理账号登录
      this.$refs.flightForm.validate(async (valid) => {
        if (valid) {
          this.flightForm.departureTime = this.fDate(
            this.flightForm.departureTime
          );
          this.flightForm.arrivalTime = this.fDate(this.flightForm.arrivalTime);

          await this.$axios
            .post("/api/flight/save", this.flightForm, {
              headers: { Authorization: "emp" },
            })
            .then((res) => {
              if (res.data.code === 1) {
                this.getFlightList();
                this.dialogVisible = false;
                this.$message.success(res.data.msg);
              } else if (res.data.code === 0) {
                this.$message.error(res.data.msg);
              }
            })
            .catch((error) => {
              // 处理请求失败的错误
              if (!error.response) {
                this.$message.error("net ero");
              }
              this.$message.error(error.response.data.msg);
            });
        } else {
          this.$message.error("请正确填写信息");
          return false;
        }
      });
    },
    async delFlight(row) {
      await this.$axios
        .delete("/api/flight/del/" + row.id, {
          headers: { Authorization: "emp" },
        })
        .then((res) => {
          if (res.data.code === 1) {
            this.getFlightList();
            this.$message.success(res.data.msg);
          } else if (res.data.code === 0) {
            this.$message.error(res.data.msg);
          }
        })
        .catch((error) => {
          // 处理请求失败的错误
          if (!error.response) {
            this.$message.error("net ero");
          }
          this.$message.error(error.response.data.msg);
        });
    },
    // 添加舱位
    addPassenger() {
      this.flightForm.cabins.push({
        cabin: "",
        price: "",
      });
    },
    // 移除舱位
    removePassenger(index) {
      this.flightForm.cabins.splice(index, 1);
    },
    //关闭dialog
    closeDialog() {
      this.dialogVisible = false;

      // 清空表单组件的验证状态
      this.$nextTick(() => {
        this.$refs.flightForm.clearValidate();
      });
    },
    //显示添加弹框
    showAddDialog() {
      this.dialogVisible = true;
      this.flightForm = {
        airline: "",
        flightNumber: "",
        cityFrom: "",
        cityTo: "",
        departureAirport: "",
        arrivalAirport: "",
        departureTime: "",
        arrivalTime: "",
        salesStatus: 0,
        cabins: [{ cabin: "", price: "" }],
      };
    },
    deleteRow(row) {
      this.$confirm(`确认删除此航班吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delFlight(row);
        })
        .catch(() => {});
    },
    //显示编辑弹框
    showEditDialog(row) {
      this.dialogVisible = true;
      this.flightForm = Object.assign({}, row);
    },
    //时区不匹配问题
    fDate(val) {
      const time = moment(val);
      // 加上 8 小时
      const timeInEightHours = time.add(0, "hours");
      // 格式化时间字符串
      return timeInEightHours.format("YYYY-MM-DD HH:mm:ss");
    },
    // 格式化当前时间
    formatDate(dateTimeStr) {
      const date = new Date(dateTimeStr);
      const year = date.getFullYear().toString().padStart(4, "0"); // 年份
      const month = (date.getMonth() + 1).toString().padStart(2, "0"); // 月份
      const day = date.getDate().toString().padStart(2, "0"); // 日
      const hours = date.getHours().toString().padStart(2, "0"); // 小时
      const minutes = date.getMinutes().toString().padStart(2, "0"); // 分钟
      // const seconds = date.getSeconds().toString().padStart(2, "0"); // 秒数

      // 构造格式化后的字符串
      // const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;

      return formattedDate;
    },
    //校验规则
    validateCabins(rule, value, callback) {
      for (let c of value) {
        if (c.cabin === "" || c.price === "") {
          callback(new Error("不能为空"));
          return;
        }
      }
      // 进行舱位校验逻辑处理，如果符合要求，则调用 callback(false)，否则调用 callback(true)
      // 示例：校验舱位名称是否重复
      let cabinNames = [];
      for (let cabin of this.flightForm.cabins) {
        if (!cabin.cabin) {
          continue;
        }
        if (cabinNames.includes(cabin.cabin)) {
          callback(new Error("舱位名称不能重复"));
          return;
        }
        cabinNames.push(cabin.cabin);
      }
      callback();
    },
  },
};
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 0px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

/* 航班样式 */
.airline-icon {
  width: 40px;
  height: 40px;
}
/* 分页样式 */
.pagination {
  text-align: center;
  margin-top: 20px;
}
</style>
